/**
 * 
 */
package com.ciukes.dynosgi.jruby;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import org.jruby.Ruby;
import org.jruby.RubyModule;
import org.jruby.internal.runtime.ValueAccessor;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.javasupport.JavaUtil;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

class ScriptExecutor {

	private Ruby runtime;

	@SuppressWarnings("unchecked")
	public ScriptExecutor(JRubyBundleConfig rubyBundleConfig) {
		try {
			runtime = JavaEmbedUtils.initialize(new ArrayList());
			runtime.getGlobalVariables().define("loader",
					new ValueAccessor(wrapToProxy(new ScriptLoader())));

			EclipseBundleFileFinder fileFinder = new EclipseBundleFileFinder(
					rubyBundleConfig.searchInBundles());
			runtime.addFileFinder(fileFinder);
		} catch (Throwable ex) {
			System.out.println();
		}
	}

	public void execute(URL script) throws ExecutionException {
		String fileName = script.getFile();
		boolean wrap = false;
		try {
			InputStream scriptStream = null;
			try {
				scriptStream = script.openStream();
				runtime.compileAndLoadFile(fileName, scriptStream, wrap);
			} finally {
				if (scriptStream != null)
					scriptStream.close();
			}
		} catch (Throwable ex) {
			throw new ExecutionException(ex);
		}
	}

	protected IRubyObject wrapToProxy(Object object) {
		IRubyObject rubyObject = JavaUtil.convertJavaToRuby(runtime, object);
		ThreadContext currentContext = runtime.getCurrentContext();
		RubyModule rubyModule = runtime.getModule("JavaUtilities");
		IRubyObject result = rubyModule.callMethod(currentContext, "wrap",
				rubyObject);
		return result;
	}
}